package com.itxh.core.handler.statement;

import com.itxh.core.config.MappedStatement;
import com.itxh.core.utils.ReflectUtils;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class DefaultResultSetHandler implements ResultSetHandler {

    @Override
    public <T> List<T> handleResultSet(ResultSet rs, MappedStatement mappedStatement) throws Exception{
        if (rs == null) {
            return null;
        }
        List<T> results = new ArrayList<>();
        Object result = null;
        Class resultTypeClass = mappedStatement.getResultTypeClass();
        while (rs.next()){
            result = ReflectUtils.newInstance(resultTypeClass);

            // 结果集元数据
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                // 下标从1开始
                String columnName = metaData.getColumnName(i);
                // 通过反射，给对象赋值
                ReflectUtils.setPropretyValue(result,columnName,rs.getObject(i));
            }

            results.add((T) result);
        }
        return results;
    }
}
